package com.group.itms.routes.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.util.Log;

public class DatabaseUtils {

	private static final String TAG = "DatabaseUtils";
	
	private static final String DB_DIRECTORY = "/data/data/com.group.itms.routes/databases/";
	
	private static final String DB_NAME = "routes.db";
	
	private static final String DB_PATH = DB_DIRECTORY + DB_NAME;
	
	public static void populateDBIfNeeded(Context c, int dbResId) throws IOException {
		if (!fileExists(DB_PATH)) {
			populateDB(c, dbResId);
		}
	}
	
	public static void populateDB(Context c, int dbResId) throws IOException {
		ensureDBDirExists();
		InputStream dbIn = c.getResources().openRawResource(dbResId);
		FileOutputStream dbOut = new FileOutputStream(DB_PATH);
		try {
			byte[] buffer = new byte[1024];
			int read;
			while ((read = dbIn.read(buffer)) != -1) {
				dbOut.write(buffer, 0, read);
			}
			Log.i(TAG, "Database populated succesfully");
		} finally {
			try {
				dbIn.close();
				dbOut.close();
			} catch (IOException e) {
				
			}
		}
	}
	
	private static void ensureDBDirExists() throws IOException {
		File dbDir = new File(DB_DIRECTORY);
		if (!dbDir.exists() && !dbDir.mkdir()) {
			String msg = "Unable to create directory: " + DB_DIRECTORY;
			Log.e(TAG, msg);
			throw new IOException(msg);
		}
	}
	
	private static boolean fileExists(String filename) {
		return new File(filename).exists();
	}

}
